﻿using System;
using System.Linq;
using System.Windows.Media;

namespace Com.Lancetinc.Evs.Helpers
{
    /// <summary>
    /// 颜色帮助类
    /// </summary>
    public class ColorHelper
    {
        public static System.Drawing.Color MediaColor2DrawingColor(Color mc)
        {
            var dc = System.Drawing.Color.FromArgb(mc.A, mc.R, mc.G, mc.B);
            return dc;
        }

        public static System.Drawing.Color[] MediaColor2DrawingColor(Color[] mcAry)
        {
            return mcAry.Select(MediaColor2DrawingColor).ToArray();
        }


        public static Color DrawingColor2MediaColor(System.Drawing.Color dc)
        {
            var mc = Color.FromArgb(dc.A, dc.R, dc.G, dc.B);
            return mc;
        }

        public static Color[] DrawingColor2MediaColor(System.Drawing.Color[] dcAry)
        {
            return dcAry.Select(DrawingColor2MediaColor).ToArray();
        }

        public static Color ConvertFromString(string colorHex)
        {
            return (Color)System.Windows.Media.ColorConverter.ConvertFromString(colorHex);
        }

        public static string ConvertToString(Color c)
        {
            return $"#{c.A:X2}{c.R:X2}{c.G:X2}{c.B:X2}";
        }

        /// <summary>
        /// 取得和当前颜色对比强烈的颜色（白或者黑）
        /// </summary>
        /// <param name="c"></param>
        /// <returns></returns>
        public static Color ContrastingColor(Color c)
        {
            double RgbSrgb(double d)
            {
                d = d / 255.0;
                return d > 0.03928
                    ? Math.Pow((d + 0.055) / 1.055, 2.4)
                    : d / 12.92;
            }

            var r = RgbSrgb(c.R);
            var g = RgbSrgb(c.G);
            var b = RgbSrgb(c.B);

            var luminance = 0.2126 * r + 0.7152 * g + 0.0722 * b;
            return luminance > 0.179 ? Colors.Black : Colors.White;
        }
    }
}
